﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Collections.Generic;

//自定义命名空间
using DreamCube.Framework.DataAccess.Basic;

namespace DreamCube.Framework.DataAccess.Sqlserver
{
    /// <summary>
    /// sqlserver数据库
    /// </summary>
    public class SqlserverDb : Database
    {
        #region "构造方法"

        internal SqlserverDb(String connectionString, SqlClientFactory providerFactory)
            : base(connectionString, providerFactory)
        { }

        #endregion

        #region "受保护方法"

        /// <summary>
        /// 分页的查询
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="primaryKey"></param>
        /// <param name="totalRecord"></param>
        /// <param name="column"></param>
        /// <param name="strWhere"></param>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        protected override DataTable Get(String tableName, Int32 pageIndex, Int32 pageSize, String primaryKey, out Int32 totalRecord, String column = "*", String strWhere = "", String orderBy = "")
        {
            totalRecord = 0;
            String sqlTemplate1 = "select top ({0}) {1} from {2} where {3} not in(select top ({4}) {3} from {2} {5} {6}) {6};";
            String sqlTemplate2 = "select count(*) from {0} {1}";
            strWhere = String.IsNullOrEmpty(strWhere) ? "" : " where " + strWhere;
            orderBy = String.IsNullOrEmpty(orderBy) ? "" : " order by " + orderBy;
            Object result = this.ExecuteScalar(String.Format(sqlTemplate2, tableName, strWhere));
            if (result != null && result != System.DBNull.Value)
                totalRecord = Convert.ToInt32(result);
            //要获取数据样式
            Int32 startIndex = (pageIndex - 1) * pageSize;
            return this.ExecuteTable(String.Format(sqlTemplate1, pageSize, column, tableName, primaryKey, startIndex, strWhere, orderBy));
        }

        #endregion

        #region "公共方法"

        /// <summary>
        /// 格式化参数名
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public override String FormatParameterName(String name)
        {
            if (!String.IsNullOrEmpty(name))
            {
                if (!name.StartsWith("@"))
                    name = "@" + name;
                return name;
            }
            return base.FormatParameterName(name);
        }

        #endregion
    }
}
